<template>
  <div class="vc-page">
    <!-- 查询条件 -->
    <searchHeader :searchConfig="searchConfig"></searchHeader>

    <!-- 操作按钮 -->
    <el-row class="vc-btns">
      <el-button @click="addFlage = true;disabled = false" size="small" type="primary">新增</el-button>
      <el-button :disabled="selectedIds.length === 0" @click="batchDel" size="small">删除</el-button>
    </el-row>

    <!-- 列表展示 -->
    <div class="vc-table">
      <Tables
        :columns="tableConfig.columns"
        :stripe="true"
        @on-selection-change="handleSelectionChange"
        ref="tables"
        v-model="tableConfig.tableData"
      />

      <!-- 分页 -->
      <el-pagination
        :current-page.sync="currentPage"
        :page-size="15"
        :total="total"
        @current-change="handleCurrentChange"
        layout="total, prev, pager, next"
        v-if="paginationShow"
      ></el-pagination>
    </div>

    <!-- 新增页面元素模态框 -->

    <el-dialog
      :before-close="cancel"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :visible.sync="addFlage"
      class="vc-dialog-form"
      destroy-on-close
      title="页面元素添加"
      width=" 480px"
    >
      <supForm :formConfig="formConfig" ref="addform" />
      <div class="dialog-footer" slot="footer">
        <el-button @click="cancel()" size="small">取消</el-button>
        <el-button :disabled="disabled" @click="addok()" size="small" type="primary">确定</el-button>
      </div>
    </el-dialog>

    <!-- 分配到权限 -->
    <el-dialog
      :before-close="cancelSpend"
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :visible.sync="spendFlag"
      class="vc-dialog-form dialog-assign-perms"
      destroy-on-close
      title="分配到权限"
      width="400px"
    >
      <div class="vc-page-parts">
        <div class="part-left" style="width: 100% !important">
          <el-tree
            :data="spendConfig.left.treeData"
            :default-expanded-keys="spendConfig.left.expandedKeys"
            :empty-text="spendConfig.left.treeEmptyText"
            :expand-on-click-node="true"
            :props="spendConfig.left.defaultProps"
            :render-content="renderContent"
            @node-click="spendConfig.left.nodeClick"
            class="org-tree"
            highlight-current
            node-key="id"
            ref="preTree"
          ></el-tree>
        </div>
        <!-- <div class="right">
          <supForm :formConfig="spendConfig.right.formConfig" ref="spendForm" />
        </div> -->
      </div>

      <div class="dialog-footer" slot="footer">
        <el-button @click="cancelSpend()" size="small">取消</el-button>
        <el-button :disabled="disabled" @click="spendOk()" size="small" type="primary">确定</el-button>
      </div>
    </el-dialog>

    <!-- 修改页面元素模态框 -->
    <el-dialog
      :close-on-click-modal="false"
      :close-on-press-escape="true"
      :visible.sync="patchFlage"
      class="vc-dialog-form"
      destroy-on-close
      title="页面元素修改"
      width=" 480px"
    >
      <supForm :formConfig="patchFormConfig" ref="addform" />
      <div class="dialog-footer" slot="footer">
        <el-button @click="patchFlage = false" size="small">取消</el-button>
        <el-button :disabled="disabled" @click="patchOk()" size="small" type="primary">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<style lang="less">
.dialog-assign-perms {
  .el-dialog__body {
    padding: 0 !important;
  }
  .vc-page-parts {
    height: 300px !important;
    .part-left {
      width: calc(40% - 1px) !important;
      margin-right: 0 !important;
      border: none !important;
      border-right: 1px solid #dfe5ee !important;
      border-radius: 0 !important;
      .org-tree {
        height: 100% !important;
      }
    }
    .right {
      width: 60%;
      padding: 20px 20px 0;
    }
  }
}
</style>

<script>
import supForm from '_c/form'
import Tables from '_c/tables'
import searchHeader from '_c/searchHeader'
import store from '@/store'
const SFGD = store.state.dic.listFormat['sfgd'].map(i => {
  i.title = i.name
  i.key = i.code
  return i
})
export default {
  name: 'page_item_management',
  components: {
    Tables,
    supForm,
    searchHeader
  },
  data() {
    return {
      spendId: '',
      disabled: false,
      // 分页
      paginationShow: true,
      currentPage: 1,
      total: 0,
      userTableData: [],
      selectedIds: [],
      entity: {},
      isExpand: false,
      // 表格渲染
      tableConfig: {
        columns: [
          {
            type: 'selection',
            width: '50'
          },
          {
            title: '序号',
            type: 'index'
          },
          {
            title: '编码',
            key: 'code'
          },
          {
            title: '名称',
            key: 'name'
          },
          {
            title: '资源路径',
            key: 'path'
          },
          {
            title: '权限名称',
            key: 'permissionName'
          },
          {
            title: '描述',
            key: 'descr'
          },
          {
            title: '操作',
            type: 'option',
            items: [
              {
                title: '修改',
                click: row => {
                  this.handleEdit(row)
                }
              },
              {
                title: '分配到权限',
                icon: 'vc-icon vc-icon-table-spendPerm',
                click: row => {
                  this.clickSpend(row)
                }
              }
            ]
          }
        ],
        tableData: []
      },
      // 搜索输入框
      searchConfig: {
        items: [
          {
            key: 'code',
            title: '编码',
            width: '140px',
            placeholder: '请输入'
          },
          {
            key: 'name',
            title: '名称',
            width: '140px',
            placeholder: '请输入'
          }
        ],
        search: params => {
          // this.findByRoleIdFuzzyPage(this.id)
          this.search(params)
        },
        reset: () => {
          this.getUsersByPage()
        },
        params: {
        }
      },
      // 新增对话框
      addFlage: false,
      formConfig: {
        items: [
          {
            title: '名称',
            required: true,
            key: 'name',
            maxlength: 20,
            message: '名称不能为空'
          },
          {
            title: '编码',
            key: 'code',
            maxlength: 30,
            required: true,
            message: '编码不能为空',
            rules: 'half'
          },
          {
            title: '资源路径',
            required: true,
            maxlength: 500,
            key: 'path',
            message: '资源路径不能为空'
          },
          {
            title: '描述',
            key: 'descr',
            type: 'textarea'
          }
        ],
        params: {
        }
      },
      // 修改对话框
      patchFlage: false,
      patchFormConfig: {
        items: [
          {
            title: '名称',
            required: true,
            key: 'name',
            maxlength: 20,
            message: '名称不能为空'
          },
          {
            title: '编码',
            key: 'code',
            required: true,
            maxlength: 30,
            message: '编码不能为空',
            rules: 'half'
          },
          {
            title: '资源路径',
            required: true,
            maxlength: 500,
            key: 'path',
            message: '资源路径不能为空'
          },
          {
            title: '描述',
            key: 'descr',
            type: 'textarea'
          }
        ],
        params: {}
      },
      // 分配权限对话框
      spendFlag: false,
      spendConfig: {
        left: {
          treeData: [],
          expandedKeys: [],
          treeEmptyText: '',
          defaultProps: {
            id: 'id',
            label: 'text',
            children: 'children',
            isLeaf: 'isLeaf'
          },
          nodeClick: data => {
            if (data.type === 'permission') {
              this.spendId = data.id
              this.spendConfig.spendParams.permissionId = data.id
            } else {
              this.$nextTick(() => {
                this.$refs.preTree.setCurrentKey(this.spendId)
              })
            }
          }
        },
        right: {
          formConfig: {
            labelWidth: '80px',
            items: [
              {
                title: '操作名称',
                key: 'name',
                required: true,
                message: '操作名称不能为空'
              },
              {
                title: '描述',
                key: 'descr',
                row: 3,
                type: 'textarea'
              }
            ],
            params: {
              name: '',
              descr: ''
            }
          }
        },
        spendParams: {}
      }
    }
  },
  computed: {
    userTypeList() {
      return this.$store.state.dic.userTypeList
    },
    userStateList() {
      return this.$store.state.dic.userStateList
    }
  },
  created() {},
  methods: {
    /*
     */
    cancelSpend() {
      // this.$refs.spendForm.resetForm()
      this.spendFlag = false
    },
    /**
     * 加载列表数据
     */
    getUsersByPage(
      params = {
        pageNum: this.currentPage,
        pageSize: this.GLOBAL.QUERY.PAGE_SIZE,
        params: {}
      }
    ) {
      Object.assign(params.params, this.searchConfig.params)
      this.$api
        .getPageItemTable({
          data: params
        })
        .then(res => {
          if (res.success) {
            if (res.data.records.length !== 0) {
              this.tableConfig.tableData = res.data.records
              this.total = res.data.total
              this.currentPage = res.data.current
            } else if (this.currentPage > 1) {
              this.currentPage--
              this.getUsersByPage()
            } else {
              this.tableConfig.tableData = []
              this.currentPage = 1
            }
          }
        })
    },
    /**
     * 点击页数
     */
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUsersByPage()
    },
    /**
     * 查询
     */
    search(params) {
      this.GLOBAL.filter.allFilterSpace(params)
      this.currentPage = 1
      this.getUsersByPage()
    },
    /**
     * 重置
     */
    reset() {
      this.searchConfig.params = this.GLOBAL.object.clearValOfObj(
        this.searchConfig.params
      )
    },
    /**
     * 复选框勾选
     */
    handleSelectionChange(val) {
      this.selectedIds = this.GLOBAL.array.selectOneKey(val, 'id')
    },
    /**
     * '删除'按钮点击事件
     */
    batchDel() {
      this.$confirmBox(this.handleDel)
    },
    /**
     * 删除
     */
    handleDel() {
      this.$api
        .deletePageItem({
          data: {
            ids: this.selectedIds
          }
        })
        .then(res => {
          this.getUsersByPage()
          if (res.success) {
            this.$notifyBox('删除成功', 'success')
          }
        })
    },
    /**
     * 操作列-修改
     */
    handleEdit(row) {
      this.patchFormConfig.params = Object.assign({}, row)
      this.disabled = false
      this.patchFlage = true
    },
    /**
     * '修改'弹出框关闭事件
     */
    closeEditDialog(val) {
      this.editDialogVisible = false
      val && this.getUsersByPage()
    },
    /*
      对话框确认
    */
    addok() {
      let flage = this.$refs.addform.save()
      if (flage) {
        this.disabled = true
        this.$api
          .addPageItem({
            data: this.formConfig.params
          })
          .then(res => {
            if (res.success) {
              this.$message.success('新增成功')
              this.reset()
              this.getUsersByPage()
              this.$refs.addform.resetForm()
              this.addFlage = false
            } else {
              this.disabled = false
            }
          })
      }
    },
    /*
      对话框取消
    */
    cancel() {
      this.$refs.addform.resetForm()
      this.addFlage = false
    },
    /*
      修改对话框
    */
    patchOk() {
      let flage = this.$refs.addform.save()

      if (flage) {
        this.disabled = true
        this.$api
          .patchPageItem({ data: this.patchFormConfig.params })
          .then(res => {
            if (res.success) {
              this.$message.success('修改页面元素成功')
              this.reset()
              this.getUsersByPage()
              this.patchFlage = false
            } else {
              this.disabled = false
            }
          })
      }
    },
    /**
      权限树
    */
    getAllRole(row) {
      this.$api
        .getMGroupTreeCurr()
        .then(res => {
          var temp1 = res.data
          for (var i = temp1.length - 1; i >= 0; i--) {
            // 添加图标
            if (temp1[i].type === 'permission') {
              temp1[i].icon = 'el-icon-tickets'
            } else {
              temp1[i].icon = 'el-icon-eleme'
            }
          }
          this.spendConfig.left.treeData = this.GLOBAL.array.transToTreeData(
            temp1
          )
          this.spendConfig.left.expandedKeys = []
          if (row.permissionId) {
            this.spendConfig.left.expandedKeys.push(row.permissionId)
            this.spendId = row.permissionId
            this.$nextTick(() => {
              this.$refs.preTree.setCurrentKey(row.permissionId)
            })
          } else {
            let expandedKeys = []
            this.getFirst(this.spendConfig.left.treeData, expandedKeys)
            this.spendId = expandedKeys[0].id
            this.spendConfig.left.expandedKeys.push(expandedKeys[0].id)
            this.spendConfig.spendParams.permissionId = expandedKeys[0].id
            this.$nextTick(() => {
              this.$refs.preTree.setCurrentKey(expandedKeys[0].id)
            })
          }
        })
    },
    clickSpend(row) {
      this.getAllRole(row)
      this.spendConfig.spendParams.resourceId = row.id
      this.spendFlag = true
      this.disabled = false
    },
    /*
      资源类型转换
    */
    transformType(obj) {
      let arr = []
      Object.keys(obj).forEach(i => {
        arr.push({
          key: i,
          title: obj[i]
        })
      })
      return arr
    },
    /*
      递归找第一个 type = 'permission'
    */
    getFirst(data, expandedKeys) {
      for (const i in data) {
        if (data[i]) {
          let node = data[i]
          if (node.type === 'permission') {
            expandedKeys.push(node)
            return
          } else if (node.children && node.children.length !== 0) {
            this.getFirst(node.children, expandedKeys)
          }
        }
      }
    },
    /*
      分配到权限
    */
    spendOk() {
      // let flage = this.$refs.spendForm.save()
      Object.assign(
        this.spendConfig.spendParams,
        this.spendConfig.right.formConfig.params,
        {
          resourceType: 'element'
        }
      )
      // if (flage) {
        this.disabled = true
        this.$api
          .relevResourcePermission({
            data: this.spendConfig.spendParams
          })
          .then(res => {
            if (res.success) {
              // this.$refs.spendForm.resetForm()
              this.spendFlag = false
              this.$notifyBox('分配到权限成功', 'success')
              this.currentPage = 1
              this.reset()
              this.getUsersByPage()
            } else {
              this.disabled = false
            }
          })
      // }
    },
    /*
      左侧树图标
    */
    renderContent(h, { node, data, store }) {
      return (
        <span>
          <i class={data.icon}></i>
          <span> {node.label}</span>
        </span>
      )
    }
  },
  mounted() {
    this.getUsersByPage()
  }
}
</script>
